package winapi

import (
	"errors"
	"log"
	"unsafe"

	"github.com/CodyGuo/win"
)

func (*Winapi) Shutdown() (err error) {
	//关机，返回nil表示关机执行成功
	var (
		hToken       win.HANDLE
		tkp          win.TOKEN_PRIVILEGES
		lpSystemName *byte
		lpName       *byte
	)
	//tmp := []byte("SeSecurityPrivilege")
	//lpName = &tmp[0]
	lpName = win.StringToBytePtr(win.SE_SHUTDOWN_NAME)
	lpSystemName = nil
	win.OpenProcessToken(win.GetCurrentProcess(), win.TOKEN_ADJUST_PRIVILEGES, &hToken)
	win.LookupPrivilegeValueA(lpSystemName, lpName, &tkp.Privileges[0].Luid)
	tkp.PrivilegeCount = 1 // one privilege to set
	tkp.Privileges[0].Attributes = win.SE_PRIVILEGE_ENABLED
	//AdjustTokenPrivileges(hToken, false, &tkp, 0, &tkp, &ReturnLength)
	win.AdjustTokenPrivileges(hToken, false, &tkp, uint32(unsafe.Sizeof(tkp)), nil, nil)
	ret2 := win.GetLastError()
	if ret2 != win.ERROR_SUCCESS {
		err = errors.New("shutdown 提升进程权限失败")
	} else {
		//log.Println("提升进程权限成功！")
		ret := win.ExitWindowsEx(win.EWX_POWEROFF|win.EWX_FORCE, 0x00000001)
		//var ret bool
		ret2 := win.GetLastError()
		if ret == false {
			//log.Println("关机失败！错误代码：", ret2)
			err = errors.New("关机失败！错误代码：" + string(ret2))
		} else {
			log.Println("关机执行成功！")
			err = nil
		}
	}
	return err
}
